package com.lanswon.qzsmk.util.pdfutil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.JobName;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.Sides;

import org.slf4j.LoggerFactory;

import com.itextpdf.text.log.Logger;


public class PrintPDFTest {
	
	private final static Logger logger = (Logger)LoggerFactory.getLogger(PrintPDFTest.class);
	
	public static void main(String args[]){
		
	FileInputStream textStream = null;
	//File file = new File("D:\\template\\receive123456_print.pdf");
	try
	{
		textStream = new FileInputStream("D:\\template\\receive123456_print.pdf");
		
	} catch (FileNotFoundException ffne)
	{
		ffne.printStackTrace();
	}
	if (textStream == null)
	{
		return;
	}
	// Set the document type
	DocFlavor myFormat = DocFlavor.INPUT_STREAM.POSTSCRIPT;
	// Create a Doc
	DocAttributeSet das = new HashDocAttributeSet();
	Doc myDoc = new SimpleDoc(textStream, myFormat, das);
	// Build a set of attributes
	PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
	HashAttributeSet has = new HashAttributeSet();
	//aset.add(new JobName(file.getName(), null));
	aset.add(new Copies(1));
	aset.add(MediaSizeName.ISO_A4);
	aset.add(Sides.ONE_SIDED);
	// discover the printers that can print the format according to the
	// instructions in the attribute set
	PrintService[] services = PrintServiceLookup.lookupPrintServices(myFormat, has);
	// Create a print job from one of the print services
	if(services.length==0){
    	System.out.println("没有打印服务");
    }
	
	//System.out.println(services.length);
	PrintService myPrinter = null;  
    for (int i = 0; i < services.length; i++) {  
    	System.out.println("service found: " + services[i]);  
        String svcName = services[i].toString();  
        if (svcName.contains("MP280")) {  
            myPrinter = services[i];  
            System.out.println("my printer found: " + svcName);  
           System.out.println("my printer found: " + myPrinter);  
           break;  
        }  
    } 
	if (services.length > 0)
	{
		System.out.println("service.name:"+myPrinter.getName());
		DocPrintJob job = myPrinter.createPrintJob();
		try
		{
			job.print(myDoc, aset);
		} catch (PrintException pe)
		{
			pe.printStackTrace();
		}
	}
}
}